<template>
  <DFModal
    ref="dfModal"
    class="computed-modal basicModal"
    :width="800"
    @register="modalRegister"
    @on-ok="okModalFn"
  >
    <template #default>
      <DFPageDetail ref="dfPageDetailRef" :pageOptions="pageOptions" />
    </template>
  </DFModal>
</template>

<script lang="ts" setup>
  import { DFModal, useModal } from '@/components/DFModal';

  import { useMixins } from '@/hooks/useMixins';

  import { typeList } from './data';
  import { computedTypeList } from '../../machine/components/data';

  const emit = defineEmits(['setRowFormulaListFn', 'register']);

  interface Props {
    orderKeyList?: any;
  }

  const props = withDefaults(defineProps<Props>(), {
    orderKeyList: () => [],
  });

  const dfPageDetailRef = ref();

  const newComputedTypeList = computedTypeList.slice(1, computedTypeList.length);

  const newTypeList = typeList.filter((item) => !['computedValue','orderKeyComputedValue'].includes(item.value));

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});

  const { t, message } = useMixins();

  const list: any = ref([]);

  const numValTypeList = computed(() => {
    return [
      ...newTypeList,
      ...list.value.slice(0, list.value.length - 1).map((item) => ({
        label: `${t('distribute.table.result')}${item.index}`,
        value: `result${item.index}`,
      })),
    ];
  });

  const pageOptions = {
    hiddenBottomBtn: true,
    routeName: 'distribute',
    list: [
      {
        hiddenTitle: true,
        title: null,
        type: 'table',
        hasSelection: true,
        ref: 'formulaList',
        columns: [
          {
            label: 'num1ValType',
            required: true,
            itemData: {
              component: 'NSelect',
              options: numValTypeList,
            },
          },
          {
            label: 'num1Val',
            itemData: {
              component: 'NInputNumber',
              maxlength: 4,
              precision: 0,
              max: 9999,
              min: 0,
            },
          },
          {
            label: 'orderKey',
            prop: 'num1OrderKey',
            itemData: {
              component: 'NSelect',
              options: computed(() => props.orderKeyList),
            },
          },
          {
            label: 'computedType',
            required: true,
            itemData: {
              component: 'NSelect',
              options: newComputedTypeList,
            },
          },
          {
            label: 'num2ValType',
            required: true,
            itemData: {
              component: 'NSelect',
              options: numValTypeList,
            },
          },
          {
            label: 'num2Val',
            itemData: {
              component: 'NInputNumber',
              maxlength: 4,
              precision: 0,
              max: 9999,
              min: 0,
            },
          },
          {
            label: 'orderKey',
            prop: 'num2OrderKey',
            itemData: {
              component: 'NSelect',
              options: computed(() => props.orderKeyList),
            },
          },
          {
            label: 'orderKeyValue',
            itemData: {
              component: 'NInput',
            },
          },
          {
            label: 'remark',
            common: true,
            itemData: {
              maxlength: 100,
            },
          },
        ],
        editTableDataChangeFn: (data) => {
          console.log(data);
          list.value = data;
        },
      },
    ],
  };

  async function openModalFn(formulaList) {
    console.log(formulaList)
    list.value = formulaList.map((item, key) => ({ ...item, index: key + 1 }));

    openModal(null, t('distribute.table.formulaList'));

    if (list.value && list.value.length) {
      nextTick(() => {
        dfPageDetailRef.value && dfPageDetailRef.value.setEditTableAllDataFn('formulaList',toRaw(list.value));
        // console.log(dfTable.value);
      });
    }
  }

  async function okModalFn() {
    const data = await dfPageDetailRef.value.getDetailRefListDataFn();

    const dataList = data['formulaList'] || [];

    const isSubmit = dataList.every((item,index) => {
      const {
        num1ValType,
        num2ValType,
        num1Val,
        num2Val,
        num1OrderKey,
        num2OrderKey,
        computedType
      } = item;

      if (num1ValType) {
        if (num1ValType === 'value') {
          if (!num1Val && num1Val !== 0) {
            message.error(t('distribute.tipMsg.numValErr').replace('xxx', '1').replace('$index',index+1));

            return false;
          }
        } else if (num1ValType === 'orderKeyValue') {
          if (!num1OrderKey) {
            message.error(t('distribute.tipMsg.numOrderKeyErr').replace('xxx', '2').replace('$index',index+1));

            return false;
          }
        }
      } else {
        message.error(t('distribute.tipMsg.numValTypeErr').replace('xxx', '1').replace('$index',index+1));

        return false;
      }

      if (!computedType) {
        message.error(t('distribute.tipMsg.computedTypeErr'));

        return false;
      }

      if (num2ValType) {
        if (num2ValType === 'value') {
          if (!num2Val && num2Val !== 0) {
            message.error(t('distribute.tipMsg.numValErr').replace('xxx', '2').replace('$index', index + 1));

            return false;
          }
        } else if (num2ValType === 'orderKeyValue') {
          if (!num2OrderKey) {
            message.error(t('distribute.tipMsg.numOrderKeyErr').replace('xxx', '2').replace('$index', index + 1));

            return false;
          }
        } else {
          message.error(t('distribute.tipMsg.numValTypeErr').replace('xxx', '2').replace('$index', index + 1));

          return false;
        }
      }

      return true;
    });

    if (isSubmit) {
      try {
        emit('setRowFormulaListFn', dataList);

        closeModal();
      } catch (e) {
        console.log(e);
      }
    }

    nextTick(() => {
      setSubLoading(false);
    });
  }

  defineExpose({
    openModalFn,
  });
</script>

<style lang="less">
  .computed-modal {
    .proCard {
      min-height: auto;
    }
  }
</style>
